package com.camerareader.mvp.image_list_page;

import android.app.Activity;
import android.app.ExpandableListActivity;
import android.content.Intent;
import android.support.annotation.IntDef;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.camerareader.R;
import com.camerareader.mvp.BaseActivity;
import com.camerareader.mvp.image_list_page.extras.ImageListAdapter;
import com.fileoperation.CommonUtils;
import com.fileoperation.FileTools;
import com.fileoperation.model.Photo;
import com.fileoperation.model.StateChangedEvent;
import com.jakewharton.rxbinding.view.RxView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

public class ImageListActivity extends BaseActivity {

    public static final int TOTAL_MODE = 1; //所有图片模式
    public static final int UPLOAD_MODE = 2;//正在上传图片模式
    public static final int SPARE_MODE = 3;//未上传图片模式

    public static final String MODE_STRING = "mode";

    @IntDef({TOTAL_MODE, UPLOAD_MODE, SPARE_MODE})
    @Retention(RetentionPolicy.SOURCE)
    public @interface PhotoListMode{}

    private int mode = -1;

    private RecyclerView imageList;
    private ImageListAdapter imageListAdapter;

    private ImageView backView;
    private ImageView allSelectedView;
    private View addToQueueBtn;
    private View bottomView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_image_list);
        initView();
    }

    @Override
    protected void onServiceConnected() {
        if (mode == UPLOAD_MODE){
            imageListAdapter.setList(uploadService.getQueueList());
        }else if (mode == SPARE_MODE){
            imageListAdapter.setList(getSparePhotos());
        }
    }

    @Override
    protected void onServiceDisconnected() {

    }

    private void initView() {
        mode = getIntent().getIntExtra(MODE_STRING, 1);
        getWindow().getDecorView().setBackgroundColor(ContextCompat.getColor(this, R.color.colorPrimary));
        imageList = (RecyclerView) findViewById(R.id.image_list);
        RecyclerView.LayoutManager layoutManager = new GridLayoutManager(this, 2);
        imageListAdapter = new ImageListAdapter(mode == SPARE_MODE);
        imageList.setLayoutManager(layoutManager);
        imageList.setAdapter(imageListAdapter);

        allSelectedView = (ImageView) findViewById(R.id.select_all);


        backView = (ImageView) findViewById(R.id.back);
        backView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });


        if (mode == SPARE_MODE){
            bottomView = findViewById(R.id.bottomView);
            addToQueueBtn = findViewById(R.id.go_upload);
            bottomView.setVisibility(View.VISIBLE);
            allSelectedView.setVisibility(View.VISIBLE);
            allSelectedView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    boolean selectAll = !imageListAdapter.isAllSelected();
                    allSelectedView.setImageResource(selectAll ? R.drawable.none_all : R.drawable.all);
                    imageListAdapter.setAllSelected(selectAll);
                }
            });

            addToQueueBtn.setVisibility(View.VISIBLE);
            addToQueueBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(imageListAdapter.getSelectedImageList() == null || imageListAdapter.getSelectedImageList().size() < 1){
                        Toast.makeText(ImageListActivity.this, "没有需要上传的文件", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    ArrayList<Photo> selectedList = imageListAdapter.getSelectedImageList();
                    uploadService.addTask(selectedList);
                }
            });

            View deleteView = findViewById(R.id.delete);
            RxView.clicks(deleteView).throttleFirst(1, TimeUnit.SECONDS).subscribe(new Action1<Void>() {
                @Override
                public void call(Void aVoid) {
                    if(imageListAdapter.getSelectedImageList() == null || imageListAdapter.getSelectedImageList().size() < 1){
                        Toast.makeText(ImageListActivity.this, "没有需要删除的文件", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    Toast.makeText(ImageListActivity.this, "开始删除...", Toast.LENGTH_SHORT).show();
                    FileTools.deletePhotos(imageListAdapter.getSelectedImageList())
                            .subscribeOn(Schedulers.newThread())
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe(new Subscriber<String>() {
                                @Override
                                public void onCompleted() {
                                    Toast.makeText(ImageListActivity.this, "删除完成！", Toast.LENGTH_SHORT).show();
                                    EventBus.getDefault().post(new StateChangedEvent());

                                }

                                @Override
                                public void onError(Throwable e) {

                                }

                                @Override
                                public void onNext(String fileName) {
                                    Log.d("ImageListActivity", "成功删除：" + fileName);
                                    EventBus.getDefault().post(new StateChangedEvent());
                                }
                            });
                    imageListAdapter.setAllSelected(false);

                }
            });
        }

        TextView arrow = (TextView) findViewById(R.id.arrow);
        CommonUtils.resizeDrawable(getResources().getDimensionPixelSize(R.dimen.right_arrow_size), 2, arrow);
    }


    public static void navigateImageListActivity(Activity activity, @PhotoListMode int mode){
        Intent intent = new Intent(activity, ImageListActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        intent.putExtra(MODE_STRING, mode);
        activity.startActivity(intent);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRefreshPhotos(StateChangedEvent event){
        switch (mode){
            case SPARE_MODE:
                imageListAdapter.setList(getSparePhotos());
                break;
            case UPLOAD_MODE:
                imageListAdapter.setList(getUploadPhotos());
                break;
            case TOTAL_MODE:
                imageListAdapter.setList(FileTools.getTotalImageList());
        }
    }

    private ArrayList<Photo> getSparePhotos(){
        ArrayList<Photo> totalList = FileTools.getTotalImageList();
        ArrayList<Photo> uploadList = getUploadPhotos();
        if (uploadList == null) return totalList;
        if (totalList == null) return null;
        for (int i = 0; i <uploadList.size(); i++){
            Photo photo = uploadList.get(i);
            if (totalList.contains(photo)){
                totalList.remove(photo);
            }
        }
        return totalList;
    }


    private ArrayList<Photo> getUploadPhotos(){
        if (uploadService == null) return null;
        return uploadService.getQueueList();
    }



    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mode == TOTAL_MODE){
            imageListAdapter.setList(FileTools.getTotalImageList());
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
    }


}
